package com.greensam.pixelengine.websocket.handle;

import com.greensam.pixelengine.constant.SpaceUserPermissionConstant;
import com.greensam.pixelengine.facade.PictureFacadeService;
import com.greensam.pixelengine.facade.SpaceFacadeService;
import com.greensam.pixelengine.facade.UserFacadeService;
import com.greensam.pixelengine.manager.auth.SpaceUserAuthManager;
import com.greensam.pixelengine.pojo.emuns.SpaceTypeEnum;
import com.greensam.pixelengine.pojo.vo.picture.response.PictureVo;
import com.greensam.pixelengine.pojo.vo.role.response.RoleVo;
import com.greensam.pixelengine.pojo.vo.space.response.SpaceVo;
import com.greensam.pixelengine.pojo.vo.user.response.LoginUserVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * WebSocket 握手拦截器
 *
 * @author Ma Chengrui
 * @since 2025/10/31 13:47
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class WsHandshakeInterceptor implements HandshakeInterceptor {

    private final UserFacadeService userFacadeService;
    private final PictureFacadeService pictureFacadeService;
    private final SpaceFacadeService spaceFacadeService;
    private final SpaceUserAuthManager spaceUserAuthManager;

    /**
     * 建立连接前先校验权限
     *
     * @param request    请求
     * @param response   响应
     * @param wsHandler  处理器
     * @param attributes 属性
     * @author Ma Chengrui
     * @since 2025/10/31
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            // 从请求中获取参数
            String pictureId = servletRequest.getParameter("pictureId");
            if (StringUtils.isBlank(pictureId)) {
                log.error("缺少图片参数，拒绝握手");
                return false;
            }
            // 获取当前用户
            LoginUserVo loginUser = userFacadeService.getLoginUserVo(servletRequest);
            if (Objects.isNull(loginUser)) {
                log.error("用户未登录，拒绝握手");
                return false;
            }
            // 校验用户是否有该图片的权限
            PictureVo picture = pictureFacadeService.getPictureById(Long.valueOf(pictureId));
            if (Objects.isNull(picture)) {
                log.error("图片不存在，拒绝握手");
                return false;
            }
            Long spaceId = picture.getSpaceId();
            SpaceVo space = null;
            if (Objects.nonNull(spaceId)) {
                space = spaceFacadeService.getSpaceById(spaceId);
                if (Objects.isNull(space)) {
                    log.error("空间不存在，拒绝握手");
                    return false;
                }
                if (space.getType() != SpaceTypeEnum.TEAM.getValue()) {
                    log.error("非团队空间，拒绝握手");
                    return false;
                }
            }
            // 如果是团队空间，并且有编辑权限，才能建立连接
            List<RoleVo> roles = loginUser.getRoles();
            Set<String> permissions = roles.stream()
                    .map(RoleVo::getValue)
                    .map(spaceUserAuthManager::listPermissionsByRole)
                    .flatMap(List::stream)
                    .collect(Collectors.toSet());
            if (!permissions.contains(SpaceUserPermissionConstant.PICTURE_EDIT)) {
                log.error("用户没有编辑图片的权限，拒绝握手");
                return false;
            }
            // 设置用户登陆信息等属性到 WebSocket Session 会话中
            attributes.put("user", loginUser);
            attributes.put("userId", loginUser.getId());
            attributes.put("pictureId", Long.valueOf(pictureId));
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
